package com.zh.chat.gui.lable;

import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JLabel;

/**
 * 
 * @author 逍遥の剑仙
 * 2013-3-3
 */
public class ImageZoomLb extends JLabel
{
	private static final long serialVersionUID = 5768002121977809949L;

	//图片路径
	private String imgPath;
	
	//显示样式
	private ShowStyle style;
	private int paintWidth = 0;
	private int paintHeight = 0;
	//图片
	private Image img;

	/**
	 * 指定长宽显示图片
	 * @param path
	 */
	public void setImage(String path, int width, int height)
	{
		imgPath = path;
		this.paintWidth = width;
		this.paintHeight = height;
		setSize(paintWidth, paintHeight);
		try
		{
			img = ImageIO.read(new File(imgPath));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		style=ShowStyle.ZOOM;
	}
	
	public void setImage(File path, int width, int height)
	{
		try {
			String imgpath = path.getCanonicalPath();
			setImage(imgpath,width,height);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 设置图片
	 * @param image
	 * @param width
	 * @param height
	 */
	public void setImage(Image image, int width, int height){
		this.img = image;
		this.paintWidth = width;
		this.paintHeight = height;
		setSize(paintWidth, paintHeight);
		style=ShowStyle.ZOOM;
	}
	
	
	/**
	 * 图片大小与JLabel大小一致
	 * @param path
	 */
	public void setImage(String path, ShowStyle style)
	{
		imgPath = path;
		this.style = style;
		try
		{
			this.img = ImageIO.read(new File(imgPath));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	/**
	 * 设置图片
	 * @param image
	 * @param style
	 */
	public void setImage(Image image, ShowStyle style){
		this.img = image;
		this.style = style;
	}
	
	/**
	 * 重写label绘画方法
	 */
	@Override
	protected void paintComponent(Graphics g)
	{
		Image img = getImage();
		
		if(ShowStyle.ORIGINALLY == style && img != null)
		{
			//图片原始像素
			g.drawImage(img, 0, 0, img.getWidth(this), img.getHeight(this), this);
		}
		else if(paintWidth!=0 && paintHeight!=0){
			//自定义长宽
			g.drawImage(img, 0, 0, paintWidth, paintHeight, this);
		}
		else if(ShowStyle.ZOOM == style && img != null)
		{
			//缩放到与label同大小
			g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
		}
		else if(style == null && img != null)
		{
			//图片原始像素
			g.drawImage(img, 0, 0, img.getWidth(this), img.getHeight(this), this);
		}

		super.paintComponent(g);
		g = null;
	}
	
	/**
	 * 得到设置图片
	 * @return
	 */
	public Image getImage()
	{
		return img;
	}
	/**
	 * 显示样式
	 * @author RuiLin.Xie - xKF24276
	 */
	public enum ShowStyle
	{
		/** 原始像素 **/
		ORIGINALLY,
		
		/** 缩放到与Label同大小 **/
		ZOOM
	}
}


